from django.db import models
from rest_framework.exceptions import ValidationError
import os
from uuid import uuid4

from users.models import CustomUser
from django.core.validators import FileExtensionValidator


def max_file_size(value):
    max_size = 100 * 1024 * 1024  # 100MB
    if value.size > max_size:
        raise ValidationError(f'文件大小不能超过 {max_size / (1024 * 1024)} MB')


def artwork_image_rename(instance, filename):
    """
    生成一个唯一的文件名，保留原始文件扩展名。
    """
    ext = filename.split('.')[-1]
    # 生成一个基于UUID的新文件名，并保留文件原始扩展名
    new_filename = f"{uuid4()}.{ext}"
    # 定义文件存储的子路径，这里使用模型的一个属性（如name）来创建子目录
    # 确保instance.name是安全的，没有特殊字符等
    sub_folder = 'artwork_images_videos'
    # 返回新的文件路径和文件名
    return os.path.join(sub_folder, new_filename)


class Artwork(models.Model):  # 艺术品
    MATERIAL_CHOICES = [
        (0, '油画'),
        (1, '水彩画'),
        (2, '素描'),
        (3, '版画'),
        (4, '雕塑'),
        (5, '其他'),
        # 添加其他材料选项...
    ]
    artist = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name='artworks',
                               verbose_name='艺术家/版权所有者')
    title = models.CharField(max_length=100, verbose_name='标题')
    description = models.TextField(verbose_name='描述')
    image = models.ImageField(upload_to=artwork_image_rename, verbose_name='图片')
    video = models.FileField(upload_to=artwork_image_rename, verbose_name='视频',
                             validators=[FileExtensionValidator(allowed_extensions=['mp4', 'avi']),
                                         max_file_size], blank=True, null=True)
    material = models.IntegerField(choices=MATERIAL_CHOICES, default=5, verbose_name='材料分类')  # 添加分类字段
    price = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='价格')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    # # 版权信息
    # owner = models.ForeignKey(CustomUser, on_delete=models.CASCADE, verbose_name='版权所有者')
    statement = models.TextField(blank=True, null=True, verbose_name='版权声明')
    license = models.CharField(max_length=100, default="使用权", verbose_name='使用许可')

    class Meta:
        verbose_name = '艺术品'
        verbose_name_plural = verbose_name
        ordering = ['title']

    def __str__(self):
        return self.title


class Order(models.Model):  # 订单
    ORDER_PENDING = 0
    ORDER_COMPLETED = 1
    ORDER_CANCELLED = 2
    ORDER_RETURN_REQUESTED = 3
    ORDER_RETURN_APPROVED = 4
    ORDER_RETURN_REJECTED = 5
    ORDER_STATUS_CHOICES = [
        (ORDER_PENDING, '待支付'),
        (ORDER_COMPLETED, '已完成'),
        (ORDER_CANCELLED, '已取消'),
        (ORDER_RETURN_REQUESTED, '退货申请中'),
        (ORDER_RETURN_APPROVED, '退货已批准'),
        (ORDER_RETURN_REJECTED, '退货被拒绝'),
    ]
    order_number = models.CharField(max_length=20, unique=True, verbose_name='订单号')
    original_artist = models.ForeignKey(CustomUser, on_delete=models.SET_NULL, null=True, blank=True,
                                        verbose_name='原始艺术家')
    buyer = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name='orders', verbose_name='买家')
    artwork = models.ForeignKey(Artwork, on_delete=models.CASCADE, verbose_name='艺术品')
    status = models.IntegerField(choices=ORDER_STATUS_CHOICES, default=0,
                                 verbose_name='订单状态')
    purchase_date = models.DateTimeField(auto_now_add=True, verbose_name='购买时间')

    # 其他订单相关字段，例如支付状态等

    class Meta:
        verbose_name = '订单'
        verbose_name_plural = verbose_name
        ordering = ['order_number']

    def __str__(self):
        return self.order_number


class Comment(models.Model):  # 评论
    artwork = models.ForeignKey(Artwork, on_delete=models.CASCADE, related_name='comments', verbose_name='艺术品')
    user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, verbose_name='用户')
    content = models.TextField(verbose_name='评论内容')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')

    class Meta:
        verbose_name = '评论'
        verbose_name_plural = verbose_name

    def __str__(self):
        return f'{self.user.username} - {self.artwork.title}'


class Rating(models.Model):  # 评分
    artwork = models.ForeignKey(Artwork, on_delete=models.CASCADE, related_name='ratings', verbose_name='艺术品')
    user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, verbose_name='用户')
    score = models.IntegerField(verbose_name='评分')

    class Meta:
        verbose_name = '评分'
        verbose_name_plural = verbose_name

    def __str__(self):
        return f'{self.user.username} - {self.artwork.title} - {self.score}'


class Message(models.Model):  # 消息
    sender = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name='sent_messages',
                               verbose_name='发送者')
    receiver = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name='received_messages',
                                 verbose_name='接收者')
    content = models.TextField(verbose_name='消息内容')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='发送时间')

    class Meta:
        verbose_name = '消息'
        verbose_name_plural = verbose_name
        ordering = ['created_at']

    def __str__(self):
        return f'{self.sender.username} -> {self.receiver.username}'
